package com.xiaolin.oa.utils;

import com.xiaolin.oa.constants.AuthConstant;
import com.xiaolin.oa.model.dto.CurrentUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @author xiaolin
 * @description 描述
 * @since 2024/8/6
 */
@Component
public class ContextUtil {
    @Autowired
    private RedisUtil redisUtil;

    /**
     * @Description: 获取当前登录用户信息
     * @Author: 林裕强
     * @Date: 2022/8/11
     */
    public CurrentUser getCurrentUser() {
        return redisUtil.get(ServletUtils.getHeader(AuthConstant.TOKEN), CurrentUser.class);
    }

    /**
     * 保存用户登录态
     *
     * @param user
     * @param expireSecond
     * @return
     */
    public String saveLoginStatus(CurrentUser user, long expireSecond) {
        String token = UUID.randomUUID().toString();
        redisUtil.set(token, user, expireSecond);
        return token;
    }

    /**
     * 刷新用户登录态
     *
     * @param user
     * @param expireSecond
     * @return
     */
    public boolean refreshLoginStatus(CurrentUser user, long expireSecond) {
        redisUtil.set(ServletUtils.getHeader(AuthConstant.TOKEN), user, expireSecond);
        return true;
    }

    /**
     * 删除用户登录态
     *
     * @return
     */
    public boolean removeLoginStatus() {
        return redisUtil.del(ServletUtils.getHeader(AuthConstant.TOKEN));
    }

    public boolean stayActive(long second) {
        return redisUtil.expire(ServletUtils.getHeader(AuthConstant.TOKEN), second);
    }
}

